<?php
namespace app\admin\controller;
use think\Controller;
//use think\Db;
use app\admin\Model\User as UserModel; 
use think\Session;
class Index extends Controller {
	public function login() {
		//登录
		$method = $this -> request -> method();
		if ($method == "GET") {
			return $this -> fetch();
		}else if($method == "POST") {
			$username = $this -> request -> param("username");
			$password = $this -> request -> param("password");
			$user = UserModel::where("username",$username)->where("password",$password)->find();	
		 if($user){
			   session("uid",$user->id);
			   $_SESSION["user"]=$user;
			   return json(["error"=>0,"message"=>"登录成功"]);
		   }else{
		   	return json(["error"=>101,"message"=>"用户名或密码错误"]);
		   }
		}
	}
	public function register(){
		//注册
	    $method=$this ->request->method();
		if($method=="GET"){
			return $this->fetch();
		}else if($method=="POST"){
			$username=$this->request->param("username");
			$email=$this->request->param("email");
			$password=$this->request->param("password");
		    $ret=UserModel::insert(["username"=>$username,"email"=>$email,"password"=>$password]);
		    if($ret==1){
		   	return json(["error"=>0,"message"=>"注册成功"]);
		   }else{
		   	return json(["error"=>101,"message"=>"注册失败"]);
		   }
		}
	}
   public function remote(){
   	$username=$this->request->param("username");
	$user=UserModel::name("user")->where("username",$username)->find();
   	return json(["valid"=>is_null($user)]);
   }
   
   public function signout() {
		//退出
		session::clear();
		return $this->success("退出成功","/");
	}
 }